package com.lx.fluplugin

import android.util.Log
import androidx.annotation.NonNull
import com.lx.flutest.flu.FluFactory

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.StandardMessageCodec

/** FlupluginPlugin */
class FlupluginPlugin: FlutterPlugin ,MethodChannel.MethodCallHandler, EventChannel.StreamHandler{
  private  lateinit var  methodChannel: MethodChannel
  //只能是原生端发送消息给flutter端
  private  lateinit var  eventChannel: EventChannel
  companion object{
    var eventSink : EventChannel.EventSink? = null
  }

  override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    methodChannel = MethodChannel(binding.binaryMessenger,"com.lx.methodChannel")
    methodChannel.setMethodCallHandler(this)
    eventChannel = EventChannel(binding.binaryMessenger,"com.lx.eventChannel")
    eventChannel.setStreamHandler(this)
//        eventChannel.setStreamHandler(object : EventChannel.StreamHandler{
//            override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
//            }
//            override fun onCancel(arguments: Any?) {
//            }
//        })
    binding.platformViewRegistry.registerViewFactory("com.lx.fluview",
      FluFactory(StandardMessageCodec.INSTANCE,binding.binaryMessenger)
    )
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    methodChannel.setMethodCallHandler(null)
    eventChannel.setStreamHandler(null)
  }

  override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
    val method = call.method
    val arguments = call.arguments
    Log.d("onMethodCall","method--->${method}")
    Log.d("onMethodCall","arguments--->${arguments}")
  }

  override fun onListen(argumentsTemp: Any?, events: EventChannel.EventSink?) {
    eventSink = events

    Log.d("onListen","EventSink argumentsTemp--->${argumentsTemp}")
    //只能是原生端发送消息给flutter端
//        var arguments = argumentsTemp as? MutableMap<String,Objects>
//        if(arguments!=null){ }
  }

  override fun onCancel(arguments: Any?) {
    eventSink = null
  }
}
